﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Portal.Systems.Render;
using Portal.Core;
using Portal.Web.Utility;
using Portal.Utility;
using Portal.Systems.Model;
using Portal.Web.Model;
using System.Web.SessionState;
using System.Web;
using System.Net;
using System.Data;
using System.Threading;

namespace Portal.Admin.Screen.Render
{
    public class LoginRenderBll
    {
        public static int LoginAttempCount = 0;
        public static string gLoginName = "";
        public static int MAX_ATTEMPTS = 3;

        public static AjaxOut Draw(string SiteId, RenderInfoCls ORenderInfo)
        {            
            AjaxOut OAjaxOut = new AjaxOut();
            SiteId = HttpUtility.HtmlEncode(SiteId);
            SiteParam OSiteParam = null;

            HttpContext.Current.Session.Clear();
            HttpContext.Current.Session.Abandon();
            HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

            try
            {
                OSiteParam = Utility.CreateSiteParam(SiteId, HttpUtility.HtmlEncode(WebConfig.XmlSiteConfigFile));
            }
            catch {}
            if (OSiteParam == null)
            {
                OAjaxOut.HtmlContent = "<div class=formLogin>" + SiteId + " not found in siteconfig.xml" + "</div>";
                return OAjaxOut;
            }

            string Html = "";
            string IpAddress = GetUserIP();
            if (string.IsNullOrEmpty(ORenderInfo.JumpUrl))
            {
                ORenderInfo.JumpUrl = "home.aspx";
            }
            OSiteParam.XmlConfigFile = HttpUtility.HtmlEncode(OSiteParam.PathRoot) + "\\xml\\siteconfig.xml";
            string AssetCode = HttpUtility.HtmlEncode(WebConfig.GetAssetCode(OSiteParam));

            string disabled = "";
            if (LoginAttempCount > 3)
            {
                disabled = "disabled";
                
                throw new Exception("Bạn đã đăng nhập không thành công quá 3 lần, truy cập lại sau 100 phút!");
            }

            try
            {
                LoginAttempCount = int.Parse(WebSessionUtility.GetSession(SiteId, gLoginName).ToString());
            }
            catch { }

            string Script =
                "<script language=javascript>\r\n" +
                "       function SetButtonVal(){    " +
                "       document.getElementById('btnLogin').disabled = true;\r\n" +
                "       setTimeout(function(){ " +
                "       document.getElementById('hd_loginCount').value = 0; " +
                "       document.getElementById('hd_loginName').value = ''; " +
                "       document.getElementById('hd_ip_address').value = 0; \r\n" +
                "       document.getElementById('btnLogin').disabled = false;\r\n" +
                "    },60000);\r\n" + // ko cho dang nhap 1p
                "    }\r\n" +
                "</script>\r\n";

            Html =
            #region javascript
 "<script language=javascript> \r\n" +
                "    function DoLogin() {\r\n" +
                "        ip_address = document.getElementById('hd_ip_address').value; \r\n" +
                "        Portal.Admin.Screen.Render.LoginRenderBll.SetLoginAttempCountByIP(ip_address).value; \r\n" +
                "        loginCount_ip = Portal.Admin.Screen.Render.LoginRenderBll.GetLoginAttempCountByIP(ip_address).value; \r\n" +
                "        if(loginCount_ip >3){ \r\n" +
                "         SetButtonVal();\r\n" +
                "         alert('Bạn đã đăng nhập không thành công quá 3 lần, truy cập lại sau 100 phút!')  \r\n" +
                "         return;\r\n" +
                "        } \r\n" +

                "       loginCount = document.getElementById('hd_loginCount').value; \r\n" +
                "       loginOld = document.getElementById('hd_loginName').value; \r\n" +
                "       LoginName = document.getElementById('txtLoginName').value;\r\n" +
                "        if(loginCount > 3){ \r\n" +
                "        if(loginOld == LoginName){ \r\n" +
                "         SetButtonVal();\r\n" +
                "         alert('Bạn đã đăng nhập không thành công quá 3 lần, truy cập lại sau 100 phút!');  \r\n" +
                "         return;\r\n" +
                "        } \r\n" +
                 "        } \r\n" +
                "        SiteId='" + SiteId + "';\r\n" +
                "        AssetCode = 'sbv'; \r\n" +
                "        Password = document.getElementById('txtPassword').value;\r\n" +

                " getverifierval =document.getElementById('captcha').value;\r\n" +
                "if(getverifierval.length == 0){\r\n" +
                    "alert('Mã xác thực không thể rỗng');\r\n" +
                    "document.getElementById('captcha').focus();\r\n" +
                    "return;\r\n" +
                "} \r\n" +

                "temp = new String(document.getElementById('dhtn').value.toString());\r\n" +

                "var getinputVerifier = temp.substring(0, 1) + temp.substring(6, 7) + temp.substring(12, 13) + temp.substring(18, 19) + temp.substring(24, 25) + temp.substring(30, 31);\r\n" +
                "var getinputCaptcha = new String(document.getElementById('captcha').value);\r\n" +

                "if (getinputCaptcha.toUpperCase() != getinputVerifier.toUpperCase()) {\r\n" +
                    "alert('Mã xác thực không đúng, xin nhập lại!');\r\n" +
                    "var rebuildCaptcha = Portal.Admin.Screen.Render.LoginRenderBll.ReCreateCaptcha().value;\r\n" +
                    "document.getElementById('divcaptcha').innerHTML = rebuildCaptcha;\r\n" +
                    "document.getElementById('captcha').focus();\r\n" +
                    "return;\r\n" +
                "}\r\n" +


                "        AjaxOut = Portal.Admin.Screen.Render.LoginRenderBll.CheckForLogin(SiteId, AssetCode, LoginName, Password).value;\r\n" +
                "        document.getElementById('hd_loginCount').value = '" + HttpUtility.HtmlEncode(LoginAttempCount) + "'; \r\n" +
                "        document.getElementById('hd_loginName').value = '" + HttpUtility.HtmlEncode(gLoginName) + "'; \r\n" +

                "        if (AjaxOut.Error) {\r\n" +
                "            alert(AjaxOut.InfoMessage);\r\n" +
                "            var rebuildCaptcha = Portal.Admin.Screen.Render.LoginRenderBll.ReCreateCaptcha().value;\r\n" +
                "            document.getElementById('divcaptcha').innerHTML = rebuildCaptcha;\r\n" +
                //"            location.reload(false);  \r\n" +
                "            return;\r\n" +
                "        }\r\n" +
                "        window.open('" + HttpUtility.HtmlEncode(ORenderInfo.JumpUrl) + "', '_self');\r\n" +
                "    }\r\n" +


                "    function LoginKeyPress(e) {\r\n" +
                "       if(e.keyCode == 13) \r\n" +
                "        {\r\n" +
                "           DoLogin();\r\n" +
                "        }\r\n" +
                "    }\r\n" +

                "</script>\r\n" +
            #endregion
 "<div class=formLogin>\r\n" +
               "    <div class=title>ĐĂNG NHẬP VÀO HỆ THỐNG QUẢN TRỊ</div>\r\n" +
               "    <div class=body>\r\n" +
               "        <div style=\"margin-top:2px;text-align:left;padding:8px;font-size:22px;\">\r\n" +
               "            <div style=\"font-size:16px;margin-top:4px;padding:4px;color:Gray;font-style:italic\">Chào mừng bạn đã đến với chức năng quản trị hệ thống</div>\r\n" +
               "        </div>\r\n" +
               "        <div class=divInfo>\r\n" +
                "       <table>\r\n" +
                "           <tr>\r\n" +
                "               <td style=\"width:120px\"><img style=\"width:120px;\" src=\"Resources/Images/login.png\">\r\n" + "</td>\r\n" +
                "               <td style=\"vertical-align:top;\">\r\n" +
                "                        <table>\r\n" +
                "                            <tr>\r\n" +
                "                                <td>Mã truy cập:</td>\r\n" +
                "                                <td><input id=txtLoginName type=textbox class=textbox ></td>\r\n" +
                "                            </tr>\r\n" +
                "                            <tr>\r\n" +
                "                                <td>Mật khẩu:</td>\r\n" +
                "                                <td><input id=txtPassword type=password onkeypress = \"javascript:LoginKeyPress(event);\" class=textbox ></td>\r\n" +
                "                            </tr>\r\n" +
                "                            <tr id=\"divcaptcha\">\r\n" +
                                                SecurityServices.CreateCaptcha() +
                "                            </tr>\r\n" +
                "                            <tr>\r\n" +
                "                                <td></td>\r\n" +
                "                                <td><input type=button id='btnLogin' " + disabled + " class=button value=\"Đăng nhập vào hệ thống\" onclick=\"javascript:DoLogin();\"></td>\r\n" +
                "                             <input type=hidden id='hd_ip_address' value='" + HttpUtility.HtmlEncode(IpAddress) + "'/> " +
                "                             <input type=hidden id='hd_loginCount' value='" + HttpUtility.HtmlEncode(LoginAttempCount) + "'/> " +
                "                             <input type=hidden id='hd_loginName' /> " +
                "                            </tr>\r\n" +
                //"                            </tr>\r\n" +
                "                        </table>\r\n" +
                "               </td>\r\n" +
                "           </tr>\r\n" +
                "   </table>\r\n" +
                "   <div class=divLoginHelp style=\"text-align:left;\">\r\n" +
                "       <ul>\r\n" +
                "           <li>Nên đổi thường xuyên mật khẩu để an toàn bảo mật</li>\r\n" +
                "           <li>Liên hệ với quản trị hệ thống nếu bạn không truy cập được</li>\r\n" +
                "           <li><span style='color:red'>Chú ý</span>: Mật khẩu nhập sai quá 3 lần tài khoản của bạn sẽ bị khóa!</li>\r\n" +
                "       </ul>\r\n" +
                "   </div>\r\n" +
                "   <div>\r\n" +
               "        </div>\r\n" +
               "    </div>\r\n" +
               "</div>\r\n" +
               "</td>\r\n" +
               "</tr>\r\n" +
               "</table>\r\n" +
               Script;
            if (!string.IsNullOrEmpty(AssetCode))
            {
                Html +=
                   "<script language=javascript>\r\n" +
                   "    document.getElementById('txtLoginName').focus();\r\n" +
                   "</script>\r\n";
            }

            OAjaxOut.HtmlContent = Html;
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static string GetUserIP()
        {
            var Request = HttpContext.Current.Request;
            string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (!string.IsNullOrEmpty(ipList))
            {
                return ipList.Split(',')[0];
            }
            return Request.ServerVariables["REMOTE_ADDR"];
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static int GetLoginAttempCountByIP(string IpAdress)
        {            
            if (HttpContext.Current.Session[IpAdress] != null)
            {
                return int.Parse(HttpUtility.HtmlEncode(HttpContext.Current.Session[IpAdress].ToString()));
            }
            else
            {
                HttpContext.Current.Session[IpAdress] = 0;
            }
            return 0;
        }

        [AjaxPro.AjaxMethod()]
        public static string ReCreateCaptcha()
        {
            return SecurityServices.CreateCaptcha();
        }

      
        public static AjaxOut ReCreateCaptchaNew(string SiteId)
        {
            AjaxOut oAjaxOut = new AjaxOut();
            string DataId = "";
            if (HttpContext.Current.Session["DataId"] != null) {
                DataId = HttpContext.Current.Session["DataId"].ToString();
            }
            string Html = string.Empty;
            string Script = 
                "<script language=javascript> \r\n" +
                "function DoDownload(DataId) {\r\n" +
                "   getverifierval =document.getElementById('captcha').value;\r\n" +
                "   if(getverifierval.length == 0){\r\n" +
                "       alert('Mã xác thực không thể rỗng');\r\n" +
                "       document.getElementById('captcha').focus();\r\n" +
                "       return;\r\n" +
                "   } \r\n" +

                "   temp = new String(document.getElementById('dhtn').value.toString());\r\n" +

                "   var getinputVerifier = temp.substring(0, 1) + temp.substring(6, 7) + temp.substring(12, 13) + temp.substring(18, 19) + temp.substring(24, 25) + temp.substring(30, 31);\r\n" +
                "   var getinputCaptcha = new String(document.getElementById('captcha').value);\r\n" +

                "   if (getinputCaptcha.toUpperCase() != getinputVerifier.toUpperCase()) {\r\n" +
                "       alert('Mã xác thực không đúng, xin nhập lại!');\r\n" +
                "       var rebuildCaptcha = Portal.Admin.Screen.Render.LoginRenderBll.ReCreateCaptcha().value;\r\n" +
                "       document.getElementById('divcaptcha').innerHTML = rebuildCaptcha;\r\n" +
                "       document.getElementById('captcha').focus();\r\n" +
                "       return;\r\n" +
                "   }\r\n" +
                "       ClientDownloadAttachFile(DataId); " +
                "   }\r\n" +

                "   function ClientDownloadAttachFile(DataId)\r\n" +
                "   {\r\n" +
                "       SiteId='" + SiteId + "';\r\n" +
                "       AjaxOut = UNBP.VBPQ.RenderService.VBPQWebRenderBll.ServerSideDownloadAttachFile(SiteId,DataId).value;\r\n" +
                "       if(AjaxOut.Error)\r\n" +
                "       {\r\n" +
                "           alert(AjaxOut.InfoMessage);\r\n" +
                "           return;\r\n" +
                "       }\r\n" +
                "       window.open(AjaxOut.RetUrl,'_blank');\r\n" +
                "       window.close();\r\n" +
                "   }\r\n" +
                "</script>\r\n";

            Html +=
                "        <div class=divInfo>\r\n" +
                "                        <table>\r\n" +
                "                            <tr id=\"divcaptcha\">\r\n" +
                                                SecurityServices.CreateCaptcha() +
                "                            </tr>\r\n" +
                   "                            <tr>\r\n" +
                "                                <td></td>\r\n" +
                "                                <td><input type=button id='btnLogin' class=button value=\"Tải xuống\" onclick=\"javascript:DoDownload('" + DataId + "');\"></td>\r\n" +
                "                            </tr>\r\n" +
                "                        </table>\r\n" +
                "        </div>" +
               Script;

            oAjaxOut.HtmlContent = Html;
            return oAjaxOut;
        }

        [AjaxPro.AjaxMethod()]
        public static void SetLoginAttempCountByIP(string IpAdress)
        {        
            if (HttpContext.Current.Session[IpAdress] != null)
            {
                int value = (int)HttpContext.Current.Session[IpAdress];
                HttpContext.Current.Session[IpAdress] = value + 1;
            }
            else
            {
                HttpContext.Current.Session[IpAdress] = 1;
            }
        }

        public static void SessionIdentifierUpdated()
        {
            HttpContext.Current.Session.RemoveAll();
            HttpContext.Current.Session.Clear();
            HttpContext.Current.Session.Abandon();
            HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);
            HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
        }


        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut CheckForLogin(
            string SiteId,
            string AssetCode,
            string LoginName,
            string Password)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            UserCls OUser = new UserCls();
            try
            {
                if (string.IsNullOrEmpty(AssetCode)) throw new Exception("Chưa xác định mã đơn vị sử dụng!");
                if (string.IsNullOrEmpty(LoginName)) throw new Exception("Chưa xác định mã truy cập!");
                if (string.IsNullOrEmpty(Password)) throw new Exception("Chưa nhập mật khẩu!");

                AuthenticateRequest(LoginName);

                OUser = null;
                OUser = SystemBussinessUtility.CreateSystemsBussinessProcess(HttpUtility.HtmlEncode(SiteId)).CheckForLogin(
                    HttpUtility.HtmlEncode(SiteId),
                    HttpUtility.HtmlEncode(AssetCode),
                    HttpUtility.HtmlEncode(LoginName.Trim()),
                    HttpUtility.HtmlEncode(Password.Trim()),
                    ref LoginAttempCount,
                    ref gLoginName);

                if (OUser == null)
                {
                    //System.Web.HttpContext.Current.Session.Clear();
                    //System.Web.HttpContext.Current.Session.Abandon();

                    HttpCookie ASPNET_Cookie = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"];
                    ASPNET_Cookie.Expires = DateTime.Now.AddDays(-1d);
                    HttpContext.Current.Response.Cookies.Add(ASPNET_Cookie);
                    throw new Exception("Mật khẩu hoặc tài khoản truy cập không hợp lệ!");
                }
                else
                {
                    HttpCookie ASPNET_Cookie = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"];
                    ASPNET_Cookie.Expires = DateTime.Now.AddMinutes(10);
                    ASPNET_Cookie.Secure = true;                    
                    HttpContext.Current.Response.Cookies.Add(ASPNET_Cookie);

                    //HttpCookie userCookie = new HttpCookie(OUser.UserId);
                    //userCookie.Expires = DateTime.Now.AddMinutes(10);                    
                    //HttpContext.Current.Response.Cookies.Add(userCookie);

                    HttpContext.Current.Session["User"] = OUser;
                    

                   
                    //WebSessionUtility.SetSession(SiteId, OUser.LoginName, LoginAttempCount);
                    //WebSessionUtility.SetSession(SiteId, "User_" + OUser.UserId, OUser.UserId);
                    //WebSessionUtility.SetCurrentLoginUser(OUser);
                }
            }
            catch (Exception ex)
            {
                OUser = null;
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
            }

            OAjaxOut.RetObject = OUser;
            return OAjaxOut;
        }

        private static void AuthenticateRequest(string LoginName)
        {
            //HttpApplication objApp = (HttpApplication)obj;
            //HttpContext objContext = (HttpContext)objApp.Context;
            // If user identity is not blank, pause for a random amount of time
            if (LoginName != "")
            {
                Random rand = new Random();
                Thread.Sleep(rand.Next(1, 10) * 1000);
            }
        }
    }
}
